using System;
using System.Collections.Generic;
using System.Reflection;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace PP.Basic
{
    /// <summary>
    /// TMPDefaultFontAssetLoader 对象
    /// </summary>
    public class TMPDefaultFontAssetLoader
    {
        private const string Tag = nameof(TMPDefaultFontAssetLoader);

        private const string DefaultFontAssetPath = "Font/Roboto_combined_v4_1 SDF.asset";

        // Private Variables Begin
        // Private Variables End
        
        // Public Methods Begin
        public static void LoadDefaultFontAsset()
        {
            // 获取 TMP_Settings 的全局实例
            TMP_Settings settingsInstance = TMP_Settings.instance;
            if (settingsInstance == null)
            {
                Debug.LogError("TMP_Settings.instance is null. This should not happen.");
                return;
            }

            var defaultFontAsset = Resources.Load<TMP_FontAsset>(DefaultFontAssetPath);
            if (!defaultFontAsset)
            {
                Debug.LogError($"{Tag}.LoadDefaultFontAsset# defaultFontAsset does not exist at {DefaultFontAssetPath}.");
                return;
            }

            if (string.Compare(TMP_Settings.defaultFontAsset.name, defaultFontAsset.name, StringComparison.OrdinalIgnoreCase) == 0)
            {
                // 如果当前的默认字体资产已经是我们要设置的字体资产，则不需要再次设置
                return;
            }

            // 通过反射获取 TMP_Settings 中私有字段 m_defaultFontAsset
            FieldInfo fontField = typeof(TMP_Settings).GetField("m_defaultFontAsset", BindingFlags.Instance | BindingFlags.NonPublic);
            if (fontField == null)
            {
                Debug.LogError("Failed to find field m_defaultFontAsset in TMP_Settings");
                return;
            }

            // 使用反射将新的字体资产赋值给 m_defaultFontAsset 字段
            fontField.SetValue(settingsInstance, defaultFontAsset);
            Debug.LogWarning($"{Tag}.LoadDefaultFontAsset# Done. Set default font asset to {DefaultFontAssetPath}.");
        }
        // Public Methods End

        // Private Methods Begin
        // Private Methods End
    }
}
